package com.mindata.blockmanager.manager;

import cn.hutool.core.bean.BeanUtil;
import com.mindata.blockmanager.bean.GridResultDto;
import com.mindata.blockmanager.bean.MemberData;
import com.mindata.blockmanager.bean.MemberVo;
import com.mindata.blockmanager.bean.QueryPage;
import com.mindata.blockmanager.model.Member;
import com.mindata.blockmanager.model.MemberGroup;
import com.mindata.blockmanager.repository.MemberGroupRepository;
import com.mindata.blockmanager.repository.MemberRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wuweifeng wrote on 2018/3/7.
 */
@Component
public class MemberManager {
    @Resource
    private MemberRepository memberRepository;
    @Resource
    private MemberGroupRepository memberGroupRepository;

    /**
     * 查询某成员的groupId
     *
     * @param memberName 成员名
     * @return 分组id
     */
    public int findGroupId(String memberName) {
        Member member = memberRepository.findFirstByName(memberName);
        if (member != null) {
            return member.getGroupId();
        }
        return -1;
    }

    public MemberData memberData(String name, String appId, String ip, int port) {
        MemberData memberData = new MemberData();
        Member member = memberRepository.findFirstByAppId(appId);
        //客户不存在
        if (member == null) {
            memberData.setCode(String.valueOf(-1));
            memberData.setMessage("客户不存在");
        } else if (!member.getName().equals(name)) {
            //name错误
            memberData.setCode(String.valueOf(-2));
            memberData.setMessage("name错误");
        } else if (!member.getIp().equals(ip)) {
            //ip错误
            memberData.setCode(String.valueOf(-3));
            memberData.setMessage("ip错误");
        } else if (member.getPort() != port) {
            // 端口错误
            memberData.setCode(String.valueOf(-2));
            memberData.setMessage("端口错误");
        } else {
            memberData.setCode(String.valueOf(0));
            //如果该member是合法的，则返回给他联盟内所有的成员列表
            List<Member> members = memberRepository.findByGroupId(member.getGroupId());
            memberData.setMembers(members);
        }
        return memberData;
    }

    public GridResultDto<MemberVo> pagingMemberList(QueryPage page) {

        if ("groupName".equals(page.getSort())) {
            page.setSort("groupId");
        }

        Sort sort = new Sort(page.getOrder(), page.getSort());    //排序
        Pageable pageable = new PageRequest(page.getPage(), page.getRows(), sort);

        //封装条件查询对象Specification
        // Root 用于获取属性字段，CriteriaQuery可以用于简单条件查询，CriteriaBuilder 用于构造复杂条件查询
        Specification<Member> specification = (root, query, cb) -> {
            //集合 用于封装查询条件
            List<Predicate> list = new ArrayList<>();
            //简单单表查询
            if (StringUtils.isNotBlank(page.getGroupId())) {
                list.add(cb.equal(root.get("groupId").as(String.class), page.getGroupId()));
            }
            if (StringUtils.isNotBlank(page.getAppId())) {
                list.add(cb.like(root.get("appId").as(String.class), "%" + page.getAppId() + "%"));
            }
            return cb.and(list.toArray(new Predicate[0]));
        };
        //调用业务层，返回Page
        Page<Member> pageData = memberRepository.findAll(specification, pageable);

        //将返回page对象转换为datagrid所需要的数据格式
        List<MemberVo> vos = new ArrayList<>();
        pageData.getContent().forEach(e -> {
            MemberVo vo = new MemberVo();
            BeanUtil.copyProperties(e, vo);
            MemberGroup memberGroup = memberGroupRepository.findByGroupId(e.getGroupId());
            if (memberGroup != null) {
                vo.setGroupName(memberGroup.getName());
            }
            vos.add(vo);
        });
        return GridResultDto.createGridResultDto(vos, pageData.getTotalElements());
    }

    public void addMember(Member member) {
        memberRepository.save(member);
    }

    public void delMember(long id) {
        memberRepository.delete(id);
    }

    public MemberVo findById(long id) {
        MemberVo vo = null;
        Member member = memberRepository.getOne(id);
        if (member != null) {
            vo = new MemberVo();
            BeanUtil.copyProperties(member, vo);
        }
        return vo;
    }

    public void updateMember(Member member) {
        memberRepository.save(member);
    }

    public Member findFirstByGroupId(int groupId) {
        return memberRepository.findFirstByGroupId(groupId);
    }
}
